package com.sys.plat.util;


import java.io.File;  
  
import javax.servlet.ServletContext;  
import javax.servlet.ServletException;  
  
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;  
import org.apache.struts.action.ActionServlet;  

 
public class StrutsUtil {  
	private static Log log = LogFactory.getLog(StrutsUtil.class);
   /** 
    * 得到所有strust配置文件的修改时间戳的和,以此来确定有没有修改过配置文件 
    * @param configFileNames 
    * @param webRootPath 
    * @return 
    */  
   public static Long getStrutsConfigTimestamp(String[] configFileNames,  
           String webRootPath) {  
       Long strutsConfigTimestamp = 0L;  
       for (String fileName : configFileNames) {  
           fileName = fileName.trim();  
           File strutsConfig = new File(webRootPath, fileName);  
           if (strutsConfig.exists())  
               strutsConfigTimestamp += strutsConfig.lastModified();  
       }  
       return strutsConfigTimestamp;  
   }  
 
   /** 
    * 自动重载strust配置文件, 
    * @param context 
    * @throws ServletException 
    */  
   public static void reloadConfig(ServletContext context) throws ServletException {  
       Long currentTimeStamp = (Long) context  
               .getAttribute("STRUSTCONFIGFILE_LASTMODIFY");  
       ActionServlet as = (ActionServlet) context  
               .getAttribute(Globals.ACTION_SERVLET_KEY);  
       String configString = as.getInitParameter("config");  
       String[] configFileNames = configString.split(",");  
       String realPath = context.getRealPath("/");  
       Long strutsConfigTimestamp = getStrutsConfigTimestamp(configFileNames,  
               realPath);  
       if (currentTimeStamp != null  
               && !currentTimeStamp.equals(strutsConfigTimestamp)) {  
           // 如果不相等重新载入配置文件  
    	   log.info("Struts context reload");
           as.destroy();  
           context.removeAttribute(Globals.REQUEST_PROCESSOR_KEY);  
           as.init();  
       }  
       context.setAttribute("STRUSTCONFIGFILE_LASTMODIFY",  
               strutsConfigTimestamp);  
   }
   
   public static void forceReload(ServletContext context) throws ServletException{
	   ActionServlet as = (ActionServlet) context  
       .getAttribute(Globals.ACTION_SERVLET_KEY); 
	   as.destroy();
       context.removeAttribute(Globals.REQUEST_PROCESSOR_KEY);  
       as.init();  
   }
}  
